<template>
  <div class="promotion-add page-container">
    <div class="page-header">
      <div class="header-left">
        <el-button link @click="goBack" class="back-btn">
          <svg class="back-icon" viewBox="0 0 24 24" fill="currentColor">
            <path
              d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"
            />
          </svg>
          返回
        </el-button>
      </div>
      <div class="header-content">
        <h1 class="page-title">新增促销活动</h1>
        <p class="page-subtitle">创建新的促销活动，配置商品和优惠规则</p>
      </div>
    </div>

    <div class="content-card">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="promotion-form"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <h3 class="section-title">基本信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="活动名称" prop="name">
                <el-input
                  v-model="form.name"
                  placeholder="请输入活动名称"
                  maxlength="128"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="活动类型" prop="type">
                <el-select
                  v-model="form.type"
                  placeholder="请选择活动类型"
                  style="width: 100%"
                  @change="handleTypeChange"
                >
                  <el-option label="满减" :value="1" />
                  <el-option label="折扣" :value="2" />
                  <el-option label="特价" :value="3" />
                  <!-- <el-option label="拼团" :value="4" /> -->
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开始时间" prop="startTime">
                <el-date-picker
                  v-model="form.startTime"
                  type="datetime"
                  placeholder="选择开始时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间" prop="endTime">
                <el-date-picker
                  v-model="form.endTime"
                  type="datetime"
                  placeholder="选择结束时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 商品选择 -->
        <div class="form-section">
          <h3 class="section-title">商品选择</h3>
          <el-form-item label="选择商品" prop="spuId">
            <el-select
              v-model="form.spuId"
              placeholder="请选择商品"
              style="width: 100%"
              filterable
              :loading="productLoading"
              @change="handleProductChange"
            >
              <el-option
                v-for="product in productList"
                :key="product.id"
                :label="product.spuName"
                :value="product.id"
              >
                <div class="product-option">
                  <img
                    v-if="
                      product.mainImageList && product.mainImageList.length > 0
                    "
                    :src="product.mainImageList[0]"
                    class="product-image"
                    alt="商品图片"
                  />
                  <div class="product-info">
                    <div class="product-name">{{ product.spuName }}</div>
                    <div class="product-category">
                      {{ product.categoryName }}
                    </div>
                  </div>
                </div>
              </el-option>
            </el-select>
          </el-form-item>

          <!-- SKU选择 -->
          <el-form-item label="选择SKU" prop="selectedSkus">
            <div class="sku-selection">
              <el-checkbox
                v-model="selectAllSkus"
                @change="handleSelectAllSkus"
                :disabled="!form.spuId"
              >
                全选所有SKU
              </el-checkbox>
              <div class="sku-list" v-if="skuList.length > 0">
                <el-checkbox-group
                  v-model="form.selectedSkus"
                  @change="handleSkuSelectionChange"
                >
                  <div v-for="sku in skuList" :key="sku.id" class="sku-item">
                    <el-checkbox :label="sku.id">
                      <div class="sku-info">
                        <div class="sku-image" v-if="sku.image">
                          <img :src="sku.image" alt="SKU图片" />
                        </div>
                        <div class="sku-details">
                          <div class="sku-name">{{ sku.skuName }}</div>
                          <div class="sku-specs" v-if="sku.specs">
                            {{ sku.specs }}
                          </div>
                          <div class="sku-price">¥{{ sku.price }}</div>
                          <div class="sku-stock">库存: {{ sku.stock }}</div>
                        </div>
                      </div>
                    </el-checkbox>
                  </div>
                </el-checkbox-group>
              </div>
              <div v-else-if="form.spuId" class="no-sku">该商品暂无SKU信息</div>
            </div>
          </el-form-item>
        </div>

        <!-- 商品配置 -->
        <div class="form-section">
          <h3 class="section-title">{{ getProductConfigTitle() }}</h3>
          <div class="product-list">
            <div
              v-for="(product, index) in form.promotionProductDTOS"
              :key="index"
              class="product-item"
            >
              <div class="product-header">
                <div class="product-title-section">
                  <span class="product-title">商品 {{ index + 1 }}</span>
                  <div class="sku-detail-info">
                    <span class="sku-name">{{
                      getSkuName(product.skuId)
                    }}</span>
                    <span v-if="getSkuSpecs(product.skuId)" class="sku-specs">
                      {{ getSkuSpecs(product.skuId) }}
                    </span>
                    <span class="sku-price-info"
                      >原价: ¥{{ getSkuPrice(product.skuId) }}</span
                    >
                  </div>
                </div>
                <div class="product-actions">
                  <el-button
                    type="danger"
                    size="small"
                    @click="removeProduct(index)"
                  >
                    删除
                  </el-button>
                </div>
              </div>

              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item
                    label="活动价"
                    :prop="`promotionProductDTOS.${index}.promotionPrice`"
                    :rules="getProductRules(index, 'promotionPrice')"
                  >
                    <el-input-number
                      v-model="product.promotionPrice"
                      :min="0"
                      :precision="2"
                      style="width: 100%"
                      :placeholder="getPricePlaceholder()"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item
                    label="促销库存"
                    :prop="`promotionProductDTOS.${index}.promotionStock`"
                    :rules="getProductRules(index, 'promotionStock')"
                  >
                    <el-input-number
                      v-model="product.promotionStock"
                      :min="1"
                      :precision="0"
                      style="width: 100%"
                      placeholder="促销库存数量"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item
                    label="限购数量"
                    :prop="`promotionProductDTOS.${index}.purchaseLimit`"
                    :rules="getProductRules(index, 'purchaseLimit')"
                  >
                    <el-input-number
                      v-model="product.purchaseLimit"
                      :min="0"
                      :precision="0"
                      style="width: 100%"
                      placeholder="每人限购数量"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
        </div>

        <!-- 规则配置 -->
        <div v-if="form.type !== 3" class="form-section">
          <h3 class="section-title">{{ getRuleConfigTitle() }}</h3>
          <div class="rule-list">
            <div
              v-for="(rule, index) in form.promotionRuleDTOS"
              :key="index"
              class="rule-item"
            >
              <div class="rule-header">
                <span class="rule-title">
                  {{ getRuleTitle(index) }}
                </span>
                <div class="rule-info">
                  <el-button
                    v-if="form.type === 1 && form.promotionRuleDTOS.length > 1"
                    type="danger"
                    size="small"
                    @click="removeRule(index)"
                  >
                    删除
                  </el-button>
                </div>
              </div>

              <!-- 满减规则 -->
              <template v-if="form.type === 1">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item
                      label="满减门槛"
                      :prop="`promotionRuleDTOS.${index}.fullAmount`"
                      :rules="getRuleRules(index, 'fullAmount')"
                    >
                      <el-input-number
                        v-model="rule.fullAmount"
                        :min="0"
                        :precision="2"
                        style="width: 100%"
                        placeholder="满减门槛金额"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item
                      label="优惠金额"
                      :prop="`promotionRuleDTOS.${index}.reduceAmount`"
                      :rules="getRuleRules(index, 'reduceAmount')"
                    >
                      <el-input-number
                        v-model="rule.reduceAmount"
                        :min="0"
                        :precision="2"
                        style="width: 100%"
                        placeholder="优惠金额"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </template>

              <!-- 折扣规则 -->
              <template v-if="form.type === 2">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item
                      label="折扣率"
                      :prop="`promotionRuleDTOS.${index}.discount`"
                      :rules="getRuleRules(index, 'discount')"
                    >
                      <el-input-number
                        v-model="rule.discount"
                        :min="0.01"
                        :max="0.99"
                        :precision="2"
                        style="width: 100%"
                        placeholder="折扣率(0.01-0.99)"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </template>

              <!-- 拼团规则 -->
              <template v-if="form.type === 4">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item
                      label="拼团人数"
                      :prop="`promotionRuleDTOS.${index}.groupSize`"
                      :rules="getRuleRules(index, 'groupSize')"
                    >
                      <el-input-number
                        v-model="rule.groupSize"
                        :min="2"
                        :precision="0"
                        style="width: 100%"
                        placeholder="拼团人数"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item
                      label="有效时长(分钟)"
                      :prop="`promotionRuleDTOS.${index}.validTime`"
                      :rules="getRuleRules(index, 'validTime')"
                    >
                      <el-input-number
                        v-model="rule.validTime"
                        :min="1"
                        :precision="0"
                        style="width: 100%"
                        placeholder="有效时长"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item
                      label="发起人优惠"
                      :prop="`promotionRuleDTOS.${index}.initiatorReduceAmount`"
                      :rules="getRuleRules(index, 'initiatorReduceAmount')"
                    >
                      <el-input-number
                        v-model="rule.initiatorReduceAmount"
                        :min="0"
                        :precision="2"
                        style="width: 100%"
                        placeholder="发起人优惠金额"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </template>
            </div>
          </div>

          <!-- 添加规则按钮 -->
          <el-button
            v-if="form.type === 1"
            type="primary"
            @click="addRule"
            class="add-rule-btn"
          >
            添加满减规则
          </el-button>
        </div>

        <!-- 活动提示 -->
        <div class="form-section">
          <h3 class="section-title">活动说明</h3>
          <div class="activity-tip">
            <el-alert
              :title="getActivityTipTitle()"
              type="info"
              :closable="false"
              show-icon
            >
              <template #default>
                <div v-html="getActivityTipContent()"></div>
              </template>
            </el-alert>
          </div>
        </div>
      </el-form>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <el-button @click="goBack">取消</el-button>
        <el-button type="primary" @click="savePromotion" :loading="saving">
          保存活动
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
// import dayjs from "dayjs";
import { postWithAuth, getWithAuth } from "@/utils/request";

const router = useRouter();
const formRef = ref();
const saving = ref(false);
const productLoading = ref(false);

// 表单数据
const form = reactive({
  name: "",
  type: undefined as number | undefined,
  spuId: undefined as string | undefined,
  selectedSkus: [] as string[],
  startTime: "",
  endTime: "",
  promotionProductDTOS: [] as any[], // 新的商品配置结构
  promotionRuleDTOS: [] as any[], // 新的规则配置结构
});

// 商品列表
const productList = ref<any[]>([]);
const skuList = ref<any[]>([]);
const selectAllSkus = ref(false);

// 表单验证规则
const rules = {
  name: [
    { required: true, message: "请输入活动名称", trigger: "blur" },
    { min: 2, max: 128, message: "长度在 2 到 128 个字符", trigger: "blur" },
  ],
  type: [{ required: true, message: "请选择活动类型", trigger: "change" }],
  spuId: [{ required: true, message: "请选择商品", trigger: "change" }],
  selectedSkus: [
    { required: true, message: "请选择商品SKU", trigger: "change" },
  ],
  startTime: [{ required: true, message: "请选择开始时间", trigger: "change" }],
  endTime: [{ required: true, message: "请选择结束时间", trigger: "change" }],
};

// 获取商品配置验证规则
const getProductRules = (_index: number, field: string) => {
  const rules: any[] = [];

  switch (field) {
    case "promotionPrice":
      rules.push({
        required: true,
        message: "请输入活动价",
        trigger: "blur",
      });
      rules.push({
        type: "number",
        min: 0,
        message: "活动价必须大于0",
        trigger: "blur",
      });
      break;
    case "promotionStock":
      rules.push({
        required: true,
        message: "请输入促销库存",
        trigger: "blur",
      });
      rules.push({
        type: "number",
        min: 1,
        message: "促销库存必须大于0",
        trigger: "blur",
      });
      break;
    case "purchaseLimit":
      rules.push({
        required: true,
        message: "请输入限购数量",
        trigger: "blur",
      });
      rules.push({
        type: "number",
        min: 0,
        message: "限购数量不能小于0",
        trigger: "blur",
      });
      break;
  }

  return rules;
};

// 获取规则配置验证规则
const getRuleRules = (_index: number, field: string) => {
  const rules: any[] = [];

  switch (field) {
    case "fullAmount":
      rules.push({
        required: true,
        message: "请输入满减门槛",
        trigger: "blur",
      });
      rules.push({
        type: "number",
        min: 0,
        message: "门槛金额必须大于0",
        trigger: "blur",
      });
      break;
    case "reduceAmount":
      rules.push({
        required: true,
        message: "请输入优惠金额",
        trigger: "blur",
      });
      rules.push({
        type: "number",
        min: 0,
        message: "优惠金额必须大于0",
        trigger: "blur",
      });
      break;
    case "discount":
      rules.push({
        required: true,
        message: "请输入折扣率",
        trigger: "blur",
      });
      rules.push({
        type: "number",
        min: 0.01,
        max: 0.99,
        message: "折扣率必须在0.01-0.99之间",
        trigger: "blur",
      });
      break;
    case "groupSize":
      rules.push({
        required: true,
        message: "请输入拼团人数",
        trigger: "blur",
      });
      rules.push({
        type: "number",
        min: 2,
        message: "拼团人数必须大于等于2",
        trigger: "blur",
      });
      break;
    case "validTime":
      rules.push({
        required: true,
        message: "请输入有效时长",
        trigger: "blur",
      });
      rules.push({
        type: "number",
        min: 1,
        message: "有效时长必须大于0",
        trigger: "blur",
      });
      break;
    case "initiatorReduceAmount":
      rules.push({
        required: true,
        message: "请输入发起人优惠金额",
        trigger: "blur",
      });
      rules.push({
        type: "number",
        min: 0,
        message: "优惠金额必须大于等于0",
        trigger: "blur",
      });
      break;
  }

  return rules;
};

// 获取商品列表
const fetchProductList = async () => {
  productLoading.value = true;
  try {
    const result = await postWithAuth("/internal/product/pageList", {
      status: 1, // 只查询上架商品
      pageNum: 1,
      pageSize: 1000, // 获取所有上架商品
    });

    if (result.code === 0) {
      productList.value = result.data.list || [];
    }
  } catch (error) {
    console.error("获取商品列表失败:", error);
    ElMessage.error("获取商品列表失败");
  } finally {
    productLoading.value = false;
  }
};

// 商品选择变化
const handleProductChange = async (productId: string) => {
  if (!productId) {
    skuList.value = [];
    form.selectedSkus = [];
    selectAllSkus.value = false;
    // 清空配置项
    form.promotionProductDTOS = [];
    form.promotionRuleDTOS = [];
    return;
  }

  try {
    const result = await getWithAuth(
      `/internal/product/skuList?spuId=${productId}`
    );

    if (result.code === 0) {
      skuList.value = result.data || [];
      form.selectedSkus = [];
      selectAllSkus.value = false;
      // 清空配置项
      form.promotionProductDTOS = [];
      form.promotionRuleDTOS = [];

      // 如果已经选择了活动类型，重新生成配置
      if (form.type) {
        regenerateConfigAfterProductChange();
        ElMessage.info("商品已变更，商品配置已自动更新");
      }
    } else {
      ElMessage.error(result.message || "获取SKU列表失败");
    }
  } catch (error) {
    console.error("获取商品SKU失败:", error);
    ElMessage.error("获取商品SKU失败");
  }
};

// 全选SKU
const handleSelectAllSkus = (checked: boolean) => {
  if (checked) {
    form.selectedSkus = skuList.value.map((sku) => sku.id);
  } else {
    form.selectedSkus = [];
  }

  // 如果已经选择了活动类型，重新生成配置
  if (form.type) {
    regenerateConfigAfterProductChange();
    ElMessage.info("SKU选择已变更，商品配置已自动更新");
  }
};

// SKU选择变化处理
const handleSkuSelectionChange = () => {
  // 如果已经选择了活动类型，重新生成配置
  if (form.type) {
    regenerateConfigAfterProductChange();
    ElMessage.info("SKU选择已变更，商品配置已自动更新");
  }
};

// 活动类型变化
const handleTypeChange = () => {
  // 清空之前的配置
  form.promotionProductDTOS = [];
  form.promotionRuleDTOS = [];

  // 根据活动类型生成商品配置
  if (form.selectedSkus.length > 0) {
    form.promotionProductDTOS = form.selectedSkus.map((skuId) => ({
      spuId: form.spuId,
      skuId: skuId,
      skuPrice: undefined, // 从对应的Sku中获取
      promotionPrice: undefined,
      promotionStock: 1,
      purchaseLimit: 0,
    }));
  }

  // 根据活动类型生成规则配置
  if (form.type === 1) {
    // 满减活动：至少一条满减规则
    form.promotionRuleDTOS = [
      {
        ruleType: 1,
        fullAmount: undefined,
        reduceAmount: undefined,
      },
    ];
  } else if (form.type === 2) {
    // 折扣活动：一条折扣规则
    form.promotionRuleDTOS = [
      {
        ruleType: 2,
        discount: undefined,
      },
    ];
  } else if (form.type === 3) {
    // 特价活动：不需要规则
    form.promotionRuleDTOS = [];
  } else if (form.type === 4) {
    // 拼团活动：一条拼团规则
    form.promotionRuleDTOS = [
      {
        ruleType: 4,
        groupSize: 3,
        validTime: 30,
        initiatorReduceAmount: 0,
      },
    ];
  }

  // 显示活动类型变更提示
  const typeNames = {
    1: "满减活动",
    2: "折扣活动",
    3: "特价活动",
    4: "拼团活动",
  };

  if (form.type) {
    ElMessage.success(`已切换到${typeNames[form.type]}，系统已自动调整配置项`);

    // 根据活动类型显示不同的提示信息
    switch (form.type) {
      case 1:
        ElMessage.info("满减活动：可设置多条满减规则，满足不同消费档位");
        break;
      case 2:
        ElMessage.info("折扣活动：设置折扣率，如0.8表示8折");
        break;
      case 3:
        ElMessage.info("特价活动：为每个SKU设置特价价格，无需促销规则");
        break;
      case 4:
        ElMessage.info("拼团活动：设置拼团人数、有效时长和发起人优惠");
        break;
    }

    // 如果有选中的SKU，提示商品配置已更新
    if (form.selectedSkus.length > 0) {
      ElMessage.info(`商品配置已更新，共${form.selectedSkus.length}个SKU`);
    }
  }
};

// 商品变更后重新生成配置
const regenerateConfigAfterProductChange = () => {
  // 根据活动类型生成商品配置
  if (form.selectedSkus.length > 0) {
    form.promotionProductDTOS = form.selectedSkus.map((skuId) => ({
      spuId: form.spuId,
      skuId: skuId,
      skuPrice: undefined, // 从对应的Sku中获取
      promotionPrice: undefined,
      promotionStock: 1,
      purchaseLimit: 0,
    }));
  }

  // 根据活动类型生成规则配置
  if (form.type === 1) {
    // 满减活动：至少一条满减规则
    form.promotionRuleDTOS = [
      {
        ruleType: 1,
        fullAmount: undefined,
        reduceAmount: undefined,
      },
    ];
  } else if (form.type === 2) {
    // 折扣活动：一条折扣规则
    form.promotionRuleDTOS = [
      {
        ruleType: 2,
        discount: undefined,
      },
    ];
  } else if (form.type === 3) {
    // 特价活动：不需要规则
    form.promotionRuleDTOS = [];
  } else if (form.type === 4) {
    // 拼团活动：一条拼团规则
    form.promotionRuleDTOS = [
      {
        ruleType: 4,
        groupSize: 3,
        validTime: 30,
        initiatorReduceAmount: 0,
      },
    ];
  }
};

// 规则类型变化
// 添加满减规则
const addRule = () => {
  // 只有满减类型可以添加多个规则
  if (form.type !== 1) {
    ElMessage.warning("只有满减类型可以添加多个规则");
    return;
  }

  form.promotionRuleDTOS.push({
    ruleType: 1,
    fullAmount: undefined,
    reduceAmount: undefined,
  });
};

// 删除满减规则
const removeRule = (index: number) => {
  // 满减类型至少需要保留一个规则
  if (form.promotionRuleDTOS.length === 1) {
    ElMessage.warning("至少需要保留一个满减规则");
    return;
  }

  form.promotionRuleDTOS.splice(index, 1);
};

// 删除商品配置
const removeProduct = (index: number) => {
  form.promotionProductDTOS.splice(index, 1);
  // 同时从选中的SKU中移除
  const removedSkuId = form.promotionProductDTOS[index]?.skuId;
  if (removedSkuId) {
    const skuIndex = form.selectedSkus.indexOf(removedSkuId);
    if (skuIndex > -1) {
      form.selectedSkus.splice(skuIndex, 1);
    }
  }
};

// 保存促销活动
const savePromotion = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    // 验证商品配置
    if (form.promotionProductDTOS.length === 0) {
      ElMessage.error("请至少添加一个商品配置");
      return;
    }

    // 验证所有商品配置都有活动价
    const invalidProduct = form.promotionProductDTOS.find(
      (product) => !product.promotionPrice || product.promotionPrice <= 0
    );
    if (invalidProduct) {
      ElMessage.error("请为所有商品配置设置有效的活动价");
      return;
    }

    // 验证规则配置（特价活动不需要规则）
    if (form.type !== 3 && form.promotionRuleDTOS.length === 0) {
      ElMessage.error("请至少添加一个规则配置");
      return;
    }

    saving.value = true;

    // 构建请求参数
    const params = {
      name: form.name,
      spuId: form.spuId,
      type: form.type,
      startTime: form.startTime,
      endTime: form.endTime,
      promotionProductDTOS: form.promotionProductDTOS,
      promotionRuleDTOS: form.promotionRuleDTOS,
    };

    const result = await postWithAuth("/internal/promotion/create", params);

    if (result.code === 0) {
      ElMessage.success("促销活动创建成功");
      router.push("/promotions");
    } else {
      ElMessage.error(result.message || "创建失败");
    }
  } catch (error) {
    console.error("保存促销活动失败:", error);
    ElMessage.error("保存失败");
  } finally {
    saving.value = false;
  }
};

// 返回列表
const goBack = () => {
  router.push("/promotions");
};

// 获取价格占位符
const getPricePlaceholder = () => {
  switch (form.type) {
    case 1:
      return "满减活动原价";
    case 2:
      return "折扣活动原价";
    case 3:
      return "特价价格";
    case 4:
      return "拼团价格";
    default:
      return "活动价";
  }
};

// 获取商品配置标题
const getProductConfigTitle = () => {
  switch (form.type) {
    case 1:
      return "满减活动商品配置";
    case 2:
      return "折扣活动商品配置";
    case 3:
      return "特价活动商品配置";
    case 4:
      return "拼团活动商品配置";
    default:
      return "商品配置";
  }
};

// 获取规则配置标题
const getRuleConfigTitle = () => {
  switch (form.type) {
    case 1:
      return "满减规则配置";
    case 2:
      return "折扣规则配置";
    case 4:
      return "拼团规则配置";
    default:
      return "规则配置";
  }
};

// 获取规则标题
const getRuleTitle = (index: number) => {
  switch (form.type) {
    case 1:
      return `满减规则 ${index + 1}`;
    case 2:
      return "折扣规则";
    case 4:
      return "拼团规则";
    default:
      return `规则 ${index + 1}`;
  }
};

// 获取活动提示标题
const getActivityTipTitle = () => {
  switch (form.type) {
    case 1:
      return "满减活动说明";
    case 2:
      return "折扣活动说明";
    case 3:
      return "特价活动说明";
    case 4:
      return "拼团活动说明";
    default:
      return "活动说明";
  }
};

// 获取活动提示内容
const getActivityTipContent = () => {
  switch (form.type) {
    case 1:
      return `
        <p>• 满减活动需要设置满减门槛和优惠金额</p>
        <p>• 可以设置多条满减规则，满足不同消费档位</p>
        <p>• 系统会自动为每个选中的SKU创建商品配置</p>
        <p>• 活动名称长度不能超过128个字符</p>
      `;
    case 2:
      return `
        <p>• 折扣活动需要设置折扣率（0.01-0.99）</p>
        <p>• 系统会自动为每个选中的SKU创建商品配置</p>
        <p>• 折扣率表示实际支付比例，如0.8表示8折</p>
        <p>• 活动名称长度不能超过128个字符</p>
      `;
    case 3:
      return `
        <p>• 特价活动需要为每个选中的SKU单独配置活动价</p>
        <p>• 系统会自动为每个SKU创建对应的商品配置</p>
        <p>• 请确保每个商品配置都设置了正确的活动价</p>
        <p>• 活动名称长度不能超过128个字符</p>
      `;
    case 4:
      return `
        <p>• 拼团活动需要设置拼团人数、有效时长和发起人优惠</p>
        <p>• 系统会自动为每个选中的SKU创建商品配置</p>
        <p>• 请确保每个商品配置都设置了正确的活动价</p>
        <p>• 活动名称长度不能超过128个字符</p>
      `;
    default:
      return `
        <p>• 请选择活动类型后查看具体说明</p>
      `;
  }
};

// 获取SKU名称
const getSkuName = (skuId: string) => {
  const sku = skuList.value.find((s) => s.id === skuId);
  return sku ? sku.skuName : skuId;
};

// 获取SKU规格信息
const getSkuSpecs = (skuId: string) => {
  const sku = skuList.value.find((s) => s.id === skuId);
  return sku ? sku.specs : "";
};

// 获取SKU原价
const getSkuPrice = (skuId: string) => {
  const sku = skuList.value.find((s) => s.id === skuId);
  return sku ? sku.price : "0.00";
};

// 页面加载时获取商品列表
onMounted(() => {
  fetchProductList();
});
</script>

<style scoped>
.promotion-add {
  padding: 24px;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  /* background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06); */
}

.header-left {
  margin-right: 24px;
}

.header-content {
  flex: 1;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #2d3748;
  margin: 0 0 8px 0;
}

.page-subtitle {
  color: #718096;
  margin: 0;
  font-size: 16px;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #64748b;
  font-weight: 500;
  transition: color 0.3s ease;
}

.back-btn:hover {
  color: #1890ff;
}

.back-icon {
  width: 16px;
  height: 16px;
}

.content-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.form-section {
  margin-bottom: 32px;
  padding-bottom: 24px;
  border-bottom: 1px solid #e2e8f0;
}

.form-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #2d3748;
  margin: 0 0 20px 0;
  padding-bottom: 8px;
  border-bottom: 2px solid #4299e1;
}

.promotion-form {
  max-width: 100%;
}

.product-option {
  display: flex;
  align-items: center;
  gap: 12px;
}

.product-image {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
}

.product-info {
  flex: 1;
}

.product-name {
  font-weight: 500;
  color: #2d3748;
  margin-bottom: 4px;
}

.product-category {
  font-size: 12px;
  color: #718096;
}

.sku-selection {
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 16px;
  background: #f7fafc;
  width: 60%;
}

.sku-list {
  margin-top: 16px;
  max-height: 200px;
  overflow-y: auto;
}

.sku-item {
  padding: 18px 0;
  border-bottom: 1px solid #edf2f7;
}

.sku-item:last-child {
  border-bottom: none;
}

.sku-info {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-left: 8px;
}

.sku-image {
  flex-shrink: 0;
}

.sku-image img {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #e2e8f0;
}

.sku-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.sku-name {
  font-weight: 500;
  color: #2d3748;
}

.sku-specs {
  color: #718096;
  font-size: 12px;
  background: #f7fafc;
  padding: 2px 6px;
  border-radius: 3px;
  display: inline-block;
  max-width: 200px;
  /* overflow: hidden; */
  text-overflow: ellipsis;
  white-space: nowrap;
}

.sku-price {
  color: #e53e3e;
  font-weight: 600;
}

.sku-stock {
  color: #718096;
  font-size: 12px;
}

.no-sku {
  text-align: center;
  color: #718096;
  font-style: italic;
  padding: 20px 0;
}

.product-config {
  margin-bottom: 24px;
}

.sub-section-title {
  font-size: 16px;
  font-weight: 600;
  color: #4a5568;
  margin: 0 0 16px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid #e2e8f0;
}

.product-title-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.sku-detail-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 14px;
}

.sku-name {
  font-weight: 600;
  color: #2d3748;
}

.sku-specs {
  color: #718096;
  background: #f7fafc;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  display: inline-block;
  max-width: 200px;
}

.sku-price-info {
  color: #e53e3e;
  font-weight: 500;
  font-size: 13px;
}

.product-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.product-list {
  margin-bottom: 16px;
}

.product-item {
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  background: #f7fafc;
}

.product-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e2e8f0;
}

.product-title {
  font-weight: 600;
  color: #2d3748;
  font-size: 16px;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.rule-config {
  margin-bottom: 24px;
}

.rule-list {
  margin-bottom: 16px;
}

.rule-item {
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  background: #f7fafc;
}

.rule-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e2e8f0;
}

.rule-title {
  font-weight: 600;
  color: #2d3748;
  font-size: 16px;
}

.rule-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.config-list {
  margin-bottom: 16px;
}

.config-item {
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  background: #f7fafc;
}

.config-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e2e8f0;
}

.config-title {
  font-weight: 600;
  color: #2d3748;
  font-size: 16px;
}

.config-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.sku-tag {
  background-color: #e2e8f0;
  color: #4299e1;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.activity-tip {
  margin-top: 16px;
}

.activity-tip .el-alert {
  border-radius: 8px;
}

.activity-tip .el-alert__content p {
  margin: 4px 0;
  font-size: 13px;
  color: #606266;
}

.add-rule-btn {
  margin-top: 16px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #e2e8f0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .promotion-add {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
    padding: 20px;
  }

  .header-left {
    margin-right: 0;
    margin-bottom: 8px;
  }

  .page-title {
    font-size: 20px;
    margin-bottom: 6px;
  }

  .page-subtitle {
    font-size: 13px;
  }

  .back-btn {
    align-self: flex-start;
    padding: 10px 20px;
  }

  .content-card {
    padding: 16px;
    border-radius: 10px;
  }

  .form-section {
    margin-bottom: 24px;
    padding-bottom: 20px;
  }

  .section-title {
    font-size: 16px;
    margin-bottom: 16px;
  }

  .sku-selection {
    padding: 12px;
  }

  .sku-list {
    max-height: 150px;
  }

  .sku-info {
    flex-direction: column;
    gap: 6px;
    align-items: flex-start;
  }

  .sku-image img {
    width: 28px;
    height: 28px;
  }

  .sku-specs {
    max-width: 120px;
    font-size: 10px;
  }

  .config-item {
    padding: 16px;
    margin-bottom: 12px;
  }

  .config-header {
    margin-bottom: 12px;
    padding-bottom: 8px;
  }

  .config-title {
    font-size: 14px;
  }

  .config-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
  }

  .sku-tag {
    font-size: 10px;
    padding: 2px 6px;
  }

  .form-actions {
    margin-top: 24px;
    padding-top: 20px;
    gap: 12px;
  }
}

@media (max-width: 480px) {
  .promotion-add {
    padding: 12px;
  }

  .page-header {
    padding: 16px;
    gap: 12px;
  }

  .header-left {
    margin-right: 0;
    margin-bottom: 6px;
  }

  .page-title {
    font-size: 18px;
  }

  .page-subtitle {
    font-size: 12px;
  }

  .back-btn {
    padding: 8px 16px;
    font-size: 13px;
  }

  .btn-icon {
    width: 14px;
    height: 14px;
  }

  .content-card {
    padding: 12px;
  }

  .form-section {
    margin-bottom: 20px;
    padding-bottom: 16px;
  }

  .section-title {
    font-size: 14px;
    margin-bottom: 12px;
  }

  .sku-selection {
    padding: 8px;
  }

  .sku-list {
    max-height: 120px;
  }

  .config-item {
    padding: 12px;
    margin-bottom: 8px;
  }

  .config-header {
    margin-bottom: 8px;
    padding-bottom: 6px;
  }

  .config-title {
    font-size: 13px;
  }

  .config-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
  }

  .sku-tag {
    font-size: 10px;
    padding: 2px 6px;
  }

  .form-actions {
    margin-top: 20px;
    padding-top: 16px;
    gap: 8px;
  }
}
</style>
